import NotAccessPage from '@/components/NotAccessPage';
import TableIntelligentRecommendation from '@/pages/cues/topic/topic/table/TableIntelligentRecommendation';
import { listCuesIndustry } from '@/services/api/api-cues-industry';
import { parse } from '@/utils/historyUtils';
import {
  DatabaseOutlined,
  HddOutlined,
  LineChartOutlined, OneToOneOutlined, ReconciliationOutlined,
  SendOutlined
} from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Badge, Card, Divider, Layout, Menu } from 'antd';
import { SelectInfo } from 'rc-menu/lib/interface';
import React, { useEffect, useState } from 'react';
import { useAccess } from 'umi';
import TableSubmit from '../../cues/topic/submit/TableSubmit';
import AddTopic from '../../cues/topic/topic/components/AddTopic';
import TableTopicAssist from '../../cues/topic/topic/table/TableTopicAssist';
import TableTopicManage from '../../cues/topic/topic/table/TableTopicManage';
import TableTopicMedia from '../../cues/topic/topic/table/TableTopicMedia';
import TableTopicRender from '../../cues/topic/topic/table/TableTopicRender';
import Analysis from './components/analysis';


export default (): React.ReactNode => {
  const access = useAccess();
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [selectMenuName, setSelectMenuName] = useState<string>('选题计划');
  const [tabActiveKey, setTabActiveKeyState] = useState<string>(
    access.线索征集x配置x管理员
      ? 'TableTopicRender'
      : access.线索征集x配置x部门需求者 || access.线索征集x配置x媒体需求者
        ? 'TableTopicMedia'
        : access.线索征集x配置x提供者
          ? 'TableTopicRender'
          :  access.线索征集x配置x区县提供者
          ? 'TableTopicRender'
          : '',
  );

  const [loading, setLoadingState] = useState<boolean>(false);

  const getMenuName = (key) => {
    let menuName = '';
    if (key === 'TableTopicRender') {
      menuName = '选题计划';
    }
    if (key === 'TableTopicManage') {
      menuName = '选题审批';
    }
    if (key === 'TableTopicMedia') {
      menuName = '我的选题计划';
    }
    if (key === 'TableTopicAssist') {
      if (access.线索征集x配置x部门需求者 || access.线索征集x配置x媒体需求者) {
        menuName = access.线索征集x配置x部门需求者 ? '联动选题计划' : '协作选题计划';
      } else {
        menuName = '联动选题计划';
      }
    }
    if (key === 'TableSubmit') {
      menuName = '报送资源';
    }
    if (key === 'IntelligentRecommendation') {
      menuName = '智能选题推荐';
    }
    return menuName
  }

  const renderBadge = (count: number, active = false) => {
    return (
      <Badge
        count={count}
        style={{
          marginBlockStart: -2,
          marginInlineStart: 4,
          color: active ? '#1890FF' : '#999',
          backgroundColor: active ? '#E6F7FF' : '#eee',
        }}
      />
    );
  };

  const menuList = () => {
    //判断是否有这个页面权限
    if (currentUser?.permissions.includes('cues:topic:page')) {
      if (access.线索征集x配置x管理员) {
        return [
          {
            label: <span>选题计划{renderBadge(0, tabActiveKey === 'TableTopicRender')}</span>,
            key: 'TableTopicRender',
            icon: <SendOutlined />,
          },
          {
            label: <span>选题审批{renderBadge(0, tabActiveKey === 'TableTopicManage')}</span>,
            key: 'TableTopicManage',
            icon: <DatabaseOutlined />,
          },
          // {
          //   label: '报送资源',
          //   key: 'TableSubmit',
          //   icon: <ProfileOutlined />,
          // },
          {
            label: <span>智能选题推荐{renderBadge(0, tabActiveKey === 'IntelligentRecommendation')}</span>,
            key: 'IntelligentRecommendation',
            icon: <ReconciliationOutlined />,
          },
          {
            label: <span>数据分析{renderBadge(0, tabActiveKey === 'analysis')}</span>,
            key: 'analysis',
            icon: <LineChartOutlined />,
          },
        ];
      } else if (access.线索征集x配置x部门需求者 || access.线索征集x配置x媒体需求者) {
        return [
          {
            label: <span>我的选题计划{renderBadge(0, tabActiveKey === 'TableTopicMedia')}</span>,
            key: 'TableTopicMedia',
            icon: <SendOutlined />,
          },
          {
            label: (
              <span>
                {access.线索征集x配置x部门需求者 ? '联动选题计划' : '协作选题计划'}
                {renderBadge(0, tabActiveKey === 'TableTopicAssist')}
              </span>
            ),
            key: 'TableTopicAssist',
            icon: <OneToOneOutlined />,
          },
          // {
          //   label: '报送资源',
          //   key: 'TableSubmit',
          //   icon: <ProfileOutlined />,
          // },
          {
            label: <span>智能选题推荐{renderBadge(0, tabActiveKey === 'IntelligentRecommendation')}</span>,
            key: 'IntelligentRecommendation',
            icon: <ReconciliationOutlined />,
          },
          {
            label: <span>数据分析{renderBadge(0, tabActiveKey === 'analysis')}</span>,
            key: 'analysis',
            icon: <LineChartOutlined />,
          },
        ];
      } else if (access.线索征集x配置x提供者) {
        return [
          {
            label: <span>选题计划{renderBadge(0, tabActiveKey === 'TableTopicRender')}</span>,
            key: 'TableTopicRender',
            icon: <SendOutlined />,
          },

          {
            label: <span>我的选题计划{renderBadge(0, tabActiveKey === 'TableTopicMedia')}</span>,
            key: 'TableTopicMedia',
            icon: <HddOutlined />,
          },
          {
            label: <span>联动选题计划{renderBadge(0, tabActiveKey === 'TableTopicAssist')}</span>,
            key: 'TableTopicAssist',
            icon: <OneToOneOutlined />,
          },
          // {
          //   label: '报送资源',
          //   key: 'TableSubmit',
          //   icon: <ProfileOutlined />,
          // },
          {
            label: <span>智能选题推荐{renderBadge(0, tabActiveKey === 'IntelligentRecommendation')}</span>,
            key: 'IntelligentRecommendation',
            icon: <ReconciliationOutlined />,
          },
          {
            label: <span>数据分析{renderBadge(0, tabActiveKey === 'analysis')}</span>,
            key: 'analysis',
            icon: <LineChartOutlined />,
          },
        ];
      }  else if (access.线索征集x配置x区县提供者) {
        return [
          {
            label: <span>选题计划{renderBadge(0, tabActiveKey === 'TableTopicRender')}</span>,
            key: 'TableTopicRender',
            icon: <SendOutlined />,
          },
          {
            label: <span>智能选题推荐{renderBadge(0, tabActiveKey === 'IntelligentRecommendation')}</span>,
            key: 'IntelligentRecommendation',
            icon: <ReconciliationOutlined />,
          },
          {
            label: <span>数据分析{renderBadge(0, tabActiveKey === 'analysis')}</span>,
            key: 'analysis',
            icon: <LineChartOutlined />,
          },
        ];
      } else {
        return [];
      }
    } else {
      return [];
    }


  };
  /**
   * 行业
   */
  const [industryIds, setIndustryIdsState] = useState<any[]>([]);

  /**
   * 加载 行业 列表
   * @param key
   */
  const loadCuesIndustryData = async () => {
    try {
      const response = await listCuesIndustry();

      setIndustryIdsState(
        response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      );
    } catch (error) { }
  };

  useEffect(() => {
    loadCuesIndustryData();
    // 父容器页面中监听message事件

  }, []);

  useEffect(() => {
    const { activeKey } = parse(location.search) as { activeKey: string };
    if (activeKey) {
      setTabActiveKeyState(activeKey)
      setSelectMenuName(getMenuName(activeKey));
    }

  }, [])


  return (
    <Layout
      hasSider
      style={{
        backgroundColor: '#F7F7F7',
        padding: '15px',
        height: '100%'
      }}
    >
      <Layout.Sider
        width={300}
        style={{
          backgroundColor: '#F7F7F7',
          overflow: 'auto',
          height: '100%',
          position: 'fixed',
          paddingBottom: 30,
        }}
      >

        <Card
          style={{
            height: '100%',
          }}
          bordered={false}
          styles={{
            body: {
              padding: '8px 15px 15px',
            },
          }}
        >
          <span style={{ fontSize: 14, display: 'flex', justifyContent: 'center', padding: 5, fontWeight: 'bold' }}>选题智能策划</span>
          <Menu
            onSelect={(info: SelectInfo) => {
              const menuName = getMenuName(info.key)
              setSelectMenuName(menuName);
              setTabActiveKeyState(info.key);
            }}
            // onClick={(info: MenuInfo) => {
            //   console.log('==onClick====', info);
            //   setTabActiveKeyState(info.key);
            // }}
            style={{ width: '100%', height: '100%', borderInlineEnd: 'none' }}
            // defaultSelectedKeys={[tabActiveKey]}
            selectedKeys={[tabActiveKey]}
            mode="vertical"
            items={menuList()}
          />
        </Card>
      </Layout.Sider>
      <Layout.Content style={{ marginLeft: '315px' }}>
        <div
          style={{
            width: 'calc(100% - 315px)',
            height: '100%',
            position: 'fixed',
            paddingBottom: 30,
            paddingRight: 30,
          }}
        >
          <Card
            style={{
              height: '100%',
              overflow: 'auto',
            }}
            styles={{
              body: {
                padding: '8px',
              },
            }}
          >
            {tabActiveKey === 'analysis' ? (
              <Analysis />
            ) : <PageContainer
              header={{
                title: `${selectMenuName}`,
                breadcrumb: {
                  items: [],
                },
                style: {
                  paddingBlockEnd: 0,
                },
                extra: (
                  <>
                    {access.线索征集x创建选题计划 && (
                      <AddTopic
                        key="add_topic"
                        onRefurbish={() => {
                          setLoadingState(true);
                        }}
                      />
                    )}
                  </>
                ),
              }}
            >
              {currentUser?.permissions.includes('cues:topic:page') ?
                <>
                  <Divider />
                  {tabActiveKey === 'TableTopicRender' ? (
                    <TableTopicRender
                      mode={1}
                      loading={loading}
                      industryIds={industryIds}
                      onRefurbish={() => {
                        setLoadingState(false);
                      }}
                    />
                  ) : tabActiveKey === 'TableTopicManage' ? (
                    <TableTopicManage
                      mode={3}
                      loading={loading}
                      industryIds={industryIds}
                      onRefurbish={() => {
                        setLoadingState(false);
                      }}
                    />
                  ) : tabActiveKey === 'TableTopicMedia' ? (
                    <TableTopicMedia
                      mode={2}
                      loading={loading}
                      industryIds={industryIds}
                      onRefurbish={() => {
                        setLoadingState(false);
                      }}
                    />
                  ) : tabActiveKey === 'TableTopicAssist' ? (
                    <TableTopicAssist
                      mode={4}
                      loading={false}
                      industryIds={[]}
                      onRefurbish={() => {
                        setLoadingState(false);
                      }}
                    />
                  ) : tabActiveKey === 'IntelligentRecommendation' ? (
                    <TableIntelligentRecommendation
                      mode={1}
                      loading={false}
                      onRefurbish={() => {
                        setLoadingState(false);
                      }}
                    />
                  )
                    // : tabActiveKey === 'analysis' ? (
                    //   <Analysis
                    //   />
                    // ) 
                    : (
                      <TableSubmit isEditable={false} />
                    )}
                </>
                : <NotAccessPage />}
            </PageContainer>}

          </Card>

        </div>
      </Layout.Content>
    </Layout>
  );
};
